/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cs575.coresystem;

import cs575.dbentities.User;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 *
 * @author bms
 */
public class UserManager {

    private EntityManager em;

    public UserManager() {
    }

    public UserManager(EntityManager em) {
        this.em = em;
    }

    public User createUser(String userName, String email, String password) {
        User user = new User(userName, password, email);
        return user;
    }
    
    public User createUserReference(int id) {
        User userX = em.getReference(User.class, id);
        return userX;
    }
        
    public User retrieveUser(int userId)
    {
        User userX = em.find(User.class, userId);
        return userX;
    }
    
    public boolean storeUser(User newUser) {
        boolean result = false;
        EntityTransaction userTransaction = em.getTransaction();
        try {
            userTransaction.begin();
            em.persist(newUser);
            result = true;
        } finally {
            userTransaction.commit();
        }
        return result;
    }

    public boolean editUser(User user) {
        boolean result = false;
        EntityTransaction userTransaction = em.getTransaction();
        try {
            userTransaction.begin();
            User userX = em.find(User.class, user.getUserId());
            userX.setUserName(user.getUserName());
            userX.setPassword(user.getPassword());
            userX.setEmail(user.getEmail());
            em.persist(userX);
            result = true;
        } finally {
            userTransaction.commit();
        }
        return result;
    }

    public boolean removeUser(User user) {
        boolean result = false;
        EntityTransaction userTransaction = em.getTransaction();
        try{
        userTransaction.begin();
        User refUser = em.getReference(User.class, user.getUserId());
        if(refUser != null)
            em.remove(refUser);
        result = true;
        }finally{
            userTransaction.commit();
        }
        return result;
    }
}
